package com.nfIt.jdbcDbutils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * ClossName:Dbutlis
 * Pakage:com.nfIt
 * Description
 *
 * @Author L
 * @Create 2024/3/6 19:25
 * @Version 2023.1.3
 */
public class Dbutlis {

    //1定义成员变量 DataSource
    private static DataSource ds;

    static {

        try {
            //加载配置文件
            Properties pro = new Properties();
            pro.load(Dbutlis.class.getClassLoader().getResourceAsStream("druid.properties"));
            //获取
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 获取连接
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }


    /**
     *
     * 释放资源
     * @param
     * @throws Exception
     */
    public static void close(ResultSet rs,Statement stmt, Connection conn){

        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if(conn != null){
            try {
                conn.close();//归还连接
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void close(Statement stmt, Connection conn){

        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        if(conn != null){
            try {
                conn.close();//归还连接
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        close(null,stmt,conn);
    }

    //获取连接池方法
    public static DataSource getDataSource(){
         return ds;
    }



    public static void main(String[] args) throws Exception {
        System.out.println(Dbutlis.getConnection());
    }



}
